package com.zw.mes.module.tecmake.service;

import com.zw.mes.entity.technology.MakeResult;
import com.zw.mes.entity.technology.ReceiveSum;
import com.zw.mes.module.system.service.LogService;
import com.zw.mes.module.technology.repository.ReceiveSumRepository;
import com.zw.mes.module.tecmake.mapper.MakeMapper;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;

import static com.zw.mes.util.BeanUtil.getNullPropertyNames;


/**
 * @author mayongfeng
 * @version 1.0.0
 * @ClassName PurchasedService.java
 * @Description TODO
 * @createTime 2021年01月29日 09:13:00
 */
@Service
@SuppressWarnings("all")
public class MakeService {

    @Autowired
    private MakeMapper makeMapper;
    @Autowired
    private LogService logService;
    @Autowired
    private ReceiveSumRepository receiveSumRepository;


    public MakeResult getSumNum(MakeResult makeResult) {
        int sumNum = 0;
        /** 查询制作件清单表数据为部长审核过的*/
        List<MakeResult> withMakeReportQuery = makeMapper.findWithMakeReportQuery(makeResult);
        Set<String> proList = new HashSet<>();

        /** 循环查询出原始单和变更单的计划条数*/
        for (MakeResult makeresult1 : withMakeReportQuery) {
            if(makeresult1.getLssueStatus()==1){
                proList.add(makeresult1.getProCode());
            }
            //原始单
            if(makeresult1.getSheetType()==1 && makeresult1.getLssueStatus()==1){
                int countNum = makeMapper.findSelectPlanNum(makeresult1.getId());
                makeresult1.setUnplanNum(countNum);
                sumNum += countNum;
                //变更单
            }else if(makeresult1.getSheetType()==2 && makeresult1.getLssueStatus()==1) {
                int countChangeNum = makeMapper.findSelectChangePlanNum(makeresult1.getId());
                makeresult1.setUnplanNum(countChangeNum);
                sumNum += countChangeNum;
            }

        }
        makeResult.setUnplanNum(sumNum);
        makeResult.setUnproNum(proList.size());
        return makeResult;


    }



    public List<MakeResult> findWithReportQuery(MakeResult makeResult) {
        int sumNum = 0;
        /** 查询制作件清单表数据为部长审核过的*/
        List<MakeResult> withMakeReportQuery = makeMapper.findWithMakeReportQuery(makeResult);

        /** 循环查询出原始单和变更单的计划条数*/
//        for (MakeResult makeResult1 : withMakeReportQuery) {
//            //原始单
//            if(makeResult1.getSheetType()==1){
//                int countNum = makeMapper.findSelectPlanNum(makeResult1.getId());
//                makeResult1.setUnplanNum(countNum);
//                sumNum += countNum;
//                //变更单
//            }else if(makeResult1.getSheetType()==2) {
//                int countChangeNum = makeMapper.findSelectChangePlanNum(makeResult1.getId());
//                makeResult1.setUnplanNum(countChangeNum);
//                sumNum += countChangeNum;
//            }
//
//        }

        return withMakeReportQuery;
    }
    /**
     * @Author mayongfeng
     * @Date 10:17 2021/2/20
     * @Description 通过Id查询该项目下的表头
     *
     **/
    public List<MakeResult> getSelectById(Integer id) {
        List<MakeResult> result1 = makeMapper.getOne(id);
        return result1;
    }

    /**
     * @Author mayongfeng
     * @Date 10:17 2021/2/20
     * @Description 通过变更状态查询明细
     *
     **/
    public List<MakeResult> getSelectDetail(Integer id,Integer sheetType) {
        List<MakeResult> results = new ArrayList<>();
        /*判断是否是变更的提报计划*/
        if(sheetType==1){
            results = makeMapper.getResultPlanList(id);
        }else if(sheetType==2){
            results = makeMapper.getResultChangeList(id);
        }
        return results;
    }

    /**
     * @Author mayongfeng
     * @Date 10:17 2021/2/20
     * @Description 通过生产令查询输出表的明细
     *
     **/
    public List<MakeResult> getResultDetail(String prodNo) {
        List<MakeResult> results = makeMapper.getResultDetail(prodNo);
        return results;
    }

    /**
     * @Author mayongfeng
     * @Date 8:31 2021/2/22
     * @Description 查询拆分页面的明细详情
     *
     **/
    public List<MakeResult> findPlanListQuery(MakeResult makeResult) {
        List<MakeResult> resultPlanList = makeMapper.getResultPlanList(makeResult.getId());
        return resultPlanList;
    }

    public static void main(String[] args) {
        int b = 3;
        int a= 5;
        System.out.println(b%a==0);
    }


    /**
     * @Author mayongfeng
     * @Date 8:31 2021/2/22
     * @Description 自动拆分功能
     *
     **/
    public List<MakeResult> findautoSplit(MakeResult makeResult) {
        logService.saveLog("制作件清单拆分功能", "拆分的主键：" + makeResult.getId());
        /*存放拆分后的list给前端*/
        List<MakeResult> newList = new ArrayList<>();
        MakeResult makeResult3 = null;
        int countMark = 0;//分配标记
        int modifyTag = 0;
        /*通过Id查询计划明细条数*/
        List<MakeResult> resultPlanList = makeMapper.getResultPlanListSearch(makeResult);
        /*通过Id查询生产令数量*/
        List<MakeResult> resultProdNum = makeMapper.getOneSearch(makeResult);
        /*主表和生产令表的数据*/
        for (MakeResult makeResult1 : resultProdNum) {
            countMark++;
           /*明细表的数据*/
            for (MakeResult makeResult2 : resultPlanList) {
                modifyTag++;
                if(makeResult2.getDrawNum()%makeResult1.getProNum()==0){
                    Integer aivNum = ((makeResult2.getDrawNum()/makeResult1.getProNum())*makeResult1.getProdNum());
                    makeResult3 = new MakeResult();
                    makeResult3.setSplitNum(aivNum);
                    copyModel(makeResult3,makeResult1, makeResult2,modifyTag);
                    newList.add(makeResult3);
                }else {
                    makeResult3 = new MakeResult();
                    makeResult3.setSplitNum(0);
                    if(countMark==1){
                        makeResult3.setSplitNum(makeResult2.getDrawNum());
                    }
                    copyModel(makeResult3,makeResult1, makeResult2,modifyTag);
                    newList.add(makeResult3);
                }
            }
        }

        return newList;
    }
    /**
     * @Author mayongfeng
     * @Date 9:33 2021/2/23
     * @Description model的复制转移
     *
     **/
    private void copyModel( MakeResult makeResult3,MakeResult makeResult1, MakeResult makeResult2,Integer modifyTag) {
        /*备注*/
        makeResult3.setRemark(makeResult2.getRemark());
        /*项目名称*/
        makeResult3.setProName(makeResult1.getProName());
        /*生产令*/
        makeResult3.setProdNo(makeResult1.getProdNo());
        /*Id*/
        makeResult3.setSheetId(makeResult1.getId());
        /*planid*/
        makeResult3.setPlanId(makeResult2.getId());
        /*生产令里面的项目数量*/
        makeResult3.setProdNum(makeResult1.getProdNum());
        /*图号*/
        makeResult3.setDrawNo(makeResult2.getDrawNo());
        /*图名*/
        makeResult3.setDrawName(makeResult2.getDrawName());
        makeResult3.setModifyTag(modifyTag);
    }


    /**
     * @Author mayongfeng
     * @Date 16:31 2021/2/23
     * @Description 验证拆分后的数量和提报的数量是否相同
     **/
    public int isSumNum(List<MakeResult> prodPlaDetList) {
        logService.saveLog("制作件清单拆分后提交功能", "");
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        for(MakeResult result: prodPlaDetList){  
            Integer planId = result.getPlanId();
            if(map.containsKey(planId)){
                map.put(planId,  ((map.get(planId)).intValue() + result.getSplitNum()));
            }else{
                map.put(planId, result.getSplitNum());
            }
        }

        /** 循环取map的值*/
        for(Map.Entry<Integer, Integer> mapz : map.entrySet()){
            /** 查询原计划单的明细*/
            MakeResult planDatil =  makeMapper.getPlanid(mapz.getKey());
            if(!planDatil.getDrawNum().toString().equals(mapz.getValue().toString())){
                return -2;
            }
        }
        /** 添加用的实体类*/
        MakeResult addResult = null;
        MakeResult sheetResult = null;
        MakeResult planResult = null;
        int i= 0;
        int sheetId = 0;
        /** 拆分成功以后存放到提报计划输出表*/
        for (MakeResult result : prodPlaDetList) {
            sheetId = result.getSheetId();
            addResult = new MakeResult();
            sheetResult = new MakeResult();
            planResult = new MakeResult();
            sheetResult = makeMapper.getSheetResult(result.getSheetId());
            planResult = makeMapper.getplanResult(result.getPlanId());
            copy(sheetResult,addResult);
            copy(planResult,addResult);
            addResult.setProdNo(result.getProdNo());
            addResult.setSplitNum(result.getSplitNum());
            addResult.setLssueStatus(1);
            addResult.setProNum(result.getProdNum());
            addResult.setPostName(sheetResult.getCreateNameOne());
            addResult.setPlanId(planResult.getId());
            addResult.setSpecial(sheetResult.getSpecial());
             i = makeMapper.addResult(addResult);

        }
        makeMapper.updateSheetId(sheetId);

        return i;
    }

    /**
     * @Author mayongfeng
     * @Date 10:09 2021/2/20
     * @Description 在输出表更改拆分后的数据的状态
     *
     **/
    public int modifyLssue(Integer resultAndSheetId,String prodNo) {
        logService.saveLog("制作件清单拆分后的任务下达", "生产令号"+prodNo);
        return makeMapper.modifyLssue(prodNo);
    }

    /**
     * @Author mayongfeng
     * @Date 13:41 2021/3/3
     * @Description 将主表的数据添加到输出表并且修改下达状态
     *
     **/
    public int addResultAndModifyLssue(Integer resultAndSheetId) {
        logService.saveLog("制作件清单一个生产令的任务下达", "主键："+resultAndSheetId);
        /*通过主表Id查询主表信息关联生产令表*/
        List<MakeResult> result = makeMapper.getOne(resultAndSheetId);

        /** 首次接收时在接收记录表里面添加记录信息*/
        ReceiveSum str = receiveSumRepository.findByProCodeAndPartAndSpecial(result.get(0).getProCode(),result.get(0).getPart(),result.get(0).getSpecial());
        /** 判断集合为不为null*/
        if(null == str || "".equals(str)){
            /** 如果记录表里面为空就向记录表里面添加接收记录*/
            ReceiveSum receiveSum = new ReceiveSum();
            receiveSum.setProCode(result.get(0).getProCode());
            receiveSum.setProName(result.get(0).getProName());
            receiveSum.setProNum(result.get(0).getProNum());
            receiveSum.setPart(result.get(0).getPart());
            receiveSum.setSpecial(result.get(0).getSpecial());
            receiveSum.setOutStatus(0);
            receiveSum.setCardStatus(0);
            receiveSum.setMakeStatus(1);
            receiveSum.setPaintStatus(0);
            receiveSumRepository.save(receiveSum);
        }else if (str.getMakeStatus()==0){
            str.setMakeStatus(1);
            receiveSumRepository.save(str);
        }

        /*通过主表Id查询原始单明细表的集合*/
        List<MakeResult> planList = makeMapper.getResultPlanList(resultAndSheetId);
        int i = 0;
        /*循环添加到输出表里面的数据*/
        for (MakeResult result1 : planList) {
            /** planId*/
            result1.setPlanId(result1.getId());
            /** sheetId*/
            result1.setSheetId(result.get(0).getId());
            /** 项目号*/
            result1.setProCode(result.get(0).getProCode());
            /** 项目名称*/
            result1.setProName(result.get(0).getProName());
            /** 项目数量*/
            result1.setProNum(result.get(0).getProdNum());
            /** 专业*/
            result1.setSpecial(result.get(0).getSpecial());
            /** 专业Id*/
            result1.setSpecialId(result.get(0).getSpecialId());
            /** 部分*/
            result1.setPart(result.get(0).getPart());
            /** 部分Id*/
            result1.setPartId(result.get(0).getPartId());
            /** 提报人*/
            result1.setPostName(result.get(0).getCreateNameOne());
            /** 提报人电话*/
            result1.setPostTel(result.get(0).getPostTel());
            /** 提报科室*/
            result1.setPostDept(result.get(0).getPostDept());
            /** 审批时间*/
            result1.setVerifyTime(result.get(0).getVerifyTime());
            /** 1=设计项目，2=非设计项目*/
            result1.setDrawType(result.get(0).getDrawType());
            /** 状态 0=删除，1=正常 */
            result1.setIsDel(0);
            /** */
            result1.setReviewer(result.get(0).getReviewer());
            /** 审核人*/
            result1.setVerifier(result.get(0).getVerifier());
            /** 下发状态：1=未下发，2=已下发*/
            result1.setLssueStatus(2);
            /** 拆分后的数量*/
            result1.setSplitNum(result1.getDrawNum());
            /** */
            result1.setLssueTime(new Date());
            /** 下达到物控的时间*/
            result1.setProdNo(result.get(0).getProdNo());
            i = makeMapper.addResult(result1);

        }
        makeMapper.updateLusseStatersBySheetId(resultAndSheetId);
        return i;

    }


    /** 主表变更数据下达并且修改到输出表*/
    public int chaSheetRelease(MakeResult makeResult) {
        int i=0;
        /** 判断被变更的主单数据是否是下达*/
        if(makeResult.getSheetId()!=null || "".equals(makeResult.getSheetId())){
            /** 通过变更主单的sheetId查询被变更的主单下达状态*/
            MakeResult sheetResult = makeMapper.getSheetResult(makeResult.getSheetId());
            /** 判断被变更的数据是否下达1=未下达,2=已下达*/
            if(sheetResult.getLssueStatus()==1){
                return -2;
            }else if(sheetResult.getLssueStatus()==2) {
                List<MakeResult> resultList = makeMapper.getResultByProCode(makeResult.getProCode());
                i = makeMapper.delResultByProCode(makeResult.getProCode());
                for (MakeResult result : resultList) {
                    result.setMakeResultId(result.getId());
                    result.setSplitNum(result.getDrawNum());
                    result.setLssueStatus(2);
                    makeMapper.addSplitResult(result);
                }
                i = makeMapper.updateLusseStatersBySheetId1(makeResult.getId());
            }

        }
        return i;

    }

/********************************************工具方法*******************************************************************/
    /**
     * 复制对象，并排除空值属性
     *
     * @param source 源对象
     * @param target 目标对象
     */
    public static void copy(Object source, Object target) {
        BeanUtils.copyProperties(source, target, getNullPropertyNames(source));
    }
    /**
     * @Author mayongfeng
     * @Date 11:04 2021/3/5
     * @Description double类型的数据进行转换在做运算
     *
     **/
    public static Double numberDouble(Double a,Double b) {
        DecimalFormat df = new DecimalFormat("0.0");
        BigDecimal b1 = new BigDecimal(df.format(a));
        BigDecimal b2 = new BigDecimal(df.format(b));
        return b1.add(b2).doubleValue();
    }

    /**
     * 执行计划暂缓
     * @param id
     * @return
     */
    public int updateVwMakeSheet(Integer id) {
        return makeMapper.updateMakeSheet(id);
    }

    /**
     * 还原暂缓计划
     * @param id
     * @return
     */
    public int updateReductSheet(Integer id,Integer lssueStatus) {
        int i = 0;
        if(lssueStatus == 3){
           i = makeMapper.updateReductSheet(id);
            logService.saveLog("还原暂缓制作件清单计划", "制作件清单主键：" + id);
        }else {
           i = makeMapper.updateIgnoreReductSheet(id);
            logService.saveLog("还原忽略制作件清单计划", "制作件清单主键：" + id);
        }
        return i;
    }

    /**
     * 查询制作件清单未分配数量
     * @return
     */
    public int selectTecmakeCount() {
        return  makeMapper.selectTecmakeCount();
    }

    /**
     * 执行计划忽略
     * @param id
     * @return
     */
    public int updateVwMakeIgnoreSheet(Integer id) {
        return makeMapper.updateMakeIgnoreSheet(id);
    }
}

